package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 菜品 服务实现类
 * </p>
 *
 * @author panheng
 * @since 2024-04-07
 */
@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 新增菜品和对应口味数据
     * @param dishDTO
     */
    @Override
    @Transactional //保证数据一致性（涉及菜品表和口味表）
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        //向菜品表插入一条数据
        dishMapper.insert(dish);

        //获取insert方法生成的主键值
        Long dishId = dish.getId();

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors != null && !flavors.isEmpty()){
            //向口味表插入n条数据
            flavors.forEach(flavor -> flavor.setDishId(dishId)); //前端无法获取到dish的主键值，因此需要我们手动添加
            dishFlavorMapper.insertBatch(flavors);
        }

    }

    /**
     * 菜品分页查询
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        int pageNo = dishPageQueryDTO.getPage(); //页码
        int pageSize = dishPageQueryDTO.getPageSize(); //页面大小
        //String name = dishPageQueryDTO.getName(); //菜品名
        //Integer status = dishPageQueryDTO.getStatus(); //状态
        //Integer categoryId = dishPageQueryDTO.getCategoryId();

        //设置分页条件
        Page<Dish> page = Page.of(pageNo, pageSize);
        //设置排序条件
        page.addOrder(new OrderItem("update_time",false));
        //设置查询条件
        /*QueryWrapper<Dish> wrapper = new QueryWrapper<Dish>()
                .like(name != null , "d.name" , name)
                .eq(status != null , "d.status" , status)
                .eq(categoryId != null , "d.category_id" , categoryId);*/

        IPage<DishVO> p = dishMapper.pageQuery(page,dishPageQueryDTO);

        //解析
        long total = p.getTotal();
        List<DishVO> records = p.getRecords();

        return new PageResult(total,records);
    }

    /**
     * 菜品批量删除
     * @param ids
     */
    @Override
    @Transactional
    public void deleteBatch(List<Long> ids) {
        // TODO 代码优化
        for (Long id : ids) {
            Dish dish = getById(id);
            //起售状态的菜品不能删除
            if(dish.getStatus() == StatusConstant.ENABLE){
                throw new DeletionNotAllowedException(dish.getName() + MessageConstant.DISH_ON_SALE);
            }

            //与套餐相关联的菜品不能删除
            Integer count = setmealDishMapper.selectByDishId(id);
            if(count > 0){
                throw new DeletionNotAllowedException(dish.getName() + MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
            }

            //删除菜品时需要连同口味表中菜品口味一起删除
            dishMapper.deleteById(id);
            dishFlavorMapper.deleteByDishId(id);
        }

    }

    /**
     * 根据id查询菜品
     * @param id
     * @return
     */
    @Override
    @Transactional
    public DishVO getVOById(Long id) {
        //查询菜品数据
        DishVO dishVO = dishMapper.getVOById(id);
        //查询fish_flavor表查找对应口味
        List<DishFlavor> flavors = dishFlavorMapper.getByDishId(id);

        dishVO.setFlavors(flavors);

        return dishVO;
    }

    /**
     * 修改菜品基本信息和对应口味信息
     * @param dishDTO
     */
    @Override
    @Transactional
    public void updateWithFlavor(DishDTO dishDTO) {
        //对菜品基本信息修改
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.update(dish);

        //对应口味表的修改
        //1.删除原有的口味数据
        dishFlavorMapper.deleteByDishId(dishDTO.getId());

        //2.修改口味数据（批量插入）
        List<DishFlavor> flavors = dishDTO.getFlavors();

        if(flavors != null && !flavors.isEmpty()){
            flavors.forEach(flavor -> flavor.setDishId(dishDTO.getId()));
            //重新批量插入口味数据
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 根据分类id查询
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> getByCategoryId(Long categoryId) {
        return dishMapper.getByCategoryId(categoryId);
    }

    /**
     * 起售或禁售菜品
     * @param status
     * @param id
     */
    @Override
    @Transactional
    public void startOrStop(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();

        dishMapper.update(dish);

        //如果是禁用菜品，则相关的套餐也会禁用
        if(status == StatusConstant.DISABLE){
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(id);
            //select setmean_id from setmeal_dish where dish_id in (?,?,?);
            List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(dishIds);

            if(setmealIds != null && !setmealIds.isEmpty() ){
                for (Long setmealId : setmealIds) {
                    Setmeal setmeal = Setmeal.builder()
                            .id(setmealId)
                            .status(StatusConstant.DISABLE)
                            .build();

                    setmealMapper.update(setmeal);
                }
            }
        }
    }

    @Override
    public List<DishVO> getWithFlavorByCategoryId(Long categoryId) {
        List<Dish> dishes = dishMapper.getByCategoryId(categoryId);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish dish : dishes) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish,dishVO);

            //根据菜品id查询对应口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(dish.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
